import io from 'socket.io-client';
import uuid from 'uuid/v4';
import MessageItem from '@/assets/scripts/MessageItem.js';
import systemConst from '@/assets/scripts/systemConst.js';
const EventNameConfig =systemConst.EventName
class MessageController{
	constructor(option){
		this.socketInstance=io(tocIM_config.socketUrl+'socketChat',{
			 transports:['websocket', 'polling'],
			 autoConnect :true

		});	//声明socketInstance实例
		this.runId=uuid();
		this.context=option.context;//环境上下文，指向调用环境（当前指向vue实例）
		this.eventNameMap={};		//socket事件集合
		this.eventNameList=[];		//解析EventNameConfig生成的的数组
		this.eventCallbackMap={};	//默认添加的回调事件集合
		this.messageList=[];
		this.init();	//初始化
	}
	init(){
		var _self = this;
		this.initEventNameMap();
		this.socketInstance.on('connected',()=> {
		    console.log("与服务连接成功 ");
		});
		this.socketInstance.on('disconnect',()=> {
		    this.socketInstance.open()
		});
		this.socketInstance.on('reconnect',()=> {
		    this.context.$toast({
			  message: '重新连接到服务器',
			  position: 'bottom',
			  duration: 2000
			});
		});
	}
	emit(eventName,data,watchEventName,watchEventCallback){
		var _self = this;
		this.messageList.push(
			new MessageItem({
				runId:_self.runId,
				eventName:eventName,
				data:data,
				watchEventName:watchEventName,
				watchEventCallback:watchEventCallback,
				timerFtn:function(data){
					_self.eventNameMap[eventName].bindScoketEvent(data)
				}
			})
		);
	}
	watch(watchEventName,watchEventCallback){
		//本质是添加一个messageList
		var _self = this;
		this.messageList.push(
			new MessageItem({
				runId:_self.runId,
				watchEventName:watchEventName,
				watchEventCallback:watchEventCallback
			})
		);
	}
	dispatchBindScoketEvent(eventName,data){
		for(var a=0;a<this.messageList.length;a++){
			var currentmessage = this.messageList[a];
			if(eventName==currentmessage.watchEventName && data.smid == currentmessage.id){					
				currentmessage.returnSuccessCallback()(data.data);
			}else if(eventName==currentmessage.watchEventName){
				currentmessage.returnSuccessCallback()(data.data);
			};
			if(currentmessage.messageType=='once'){
				this.messageList.splice(a--,1);
			}
		};
	}
	getContextCallback(eventName){
	 	return this.eventCallbackMap[eventName];
	}
	initEventNameMap(){
		var _self =this;
		this.eventNameList=interatorObj(EventNameConfig);
		this.eventNameList.forEach(item =>{
			var keyName=Object.keys(item)[0];
			_self.eventNameMap[keyName]={
				id:item[keyName].id,
				type:item[keyName].type,
				bindScoketEvent:item[keyName].type=='req'?function(data){
					_self.socketInstance.emit(item[keyName].id,data);
				}:function(){
					_self.socketInstance.on(item[keyName].id,function(data){
						_self.getContextCallback(keyName)(data);
					});
				}
			};
		});
		this.initScoketEvent();
	}
	initScoketEvent(){
		Object.keys(this.eventNameMap).forEach( item=>{
			if(this.eventNameMap[item].type=='res'){
				//设置默认接收回调方法为调用dispatchBindScoketEvent
				this.eventCallbackMap[item]= res =>{
					this.dispatchBindScoketEvent(item,res);
				};
				this.eventNameMap[item].bindScoketEvent();	//注册监听事件
			};
		});
	}
}
var interatorObj=function(obj){
	var result=[];
	Object.keys(obj).forEach(function(item,index){
		Object.keys(obj[item]).forEach(function(items,index){
			result.push({[item+'_'+items]:{
				id:obj[item][items],
				type:items.indexOf('Server')!=-1?'res':'req'
			}});
		});
	});
	return result;
};

export default MessageController